package com.example.demo.netty.netty5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Server {
    public static void main(String[] args) {
        //服務類
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        serverBootstrap.group(boss,worker);
        serverBootstrap.channel(NioServerSocketChannel.class);

        serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                channel.pipeline().addLast(new StringDecoder());
                channel.pipeline().addLast(new StringEncoder());
                channel.pipeline().addLast(new ServerHandler());
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,2048);//serverSocket接受数据的队列的大小
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);//对socket维持连接的活跃 清楚死链接
        serverBootstrap.childOption(ChannelOption.TCP_NODELAY,true);//对socket关闭延迟发送
        ChannelFuture future = serverBootstrap.bind(10101);
        try {
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
